/**
 * Created by ZHOUSH on 1/19/2016.
 */

var Promise = require('promise');
var fs = require('fs');
var oracledb = require('oracledb');
var connutil = require('../../tool/connection');
var connstr = require('../../tool/connstr');
var conn = connstr.use('LLP', 'PRD', 'SUPP');
var init_module = function (app) {
    var midQuery = function (parseSql) {
        return function (req, res) {
            var query = req.body;
            oracledb.getConnection(conn, function (err, conn) {
                if (err) {
                    res.status(500).send(err.toString());
                } else {
                    connutil.execute(conn, parseSql(query.sql)).then(function (data) {
                        res.json(data);
                        conn.release(function (err) {
                            if (err) {
                                res.status(500).send(err.toString());
                            }
                        });
                        res.end();
                    }).catch(function (err) {
                        res.status(500).json({
                            code: 'ERR_DB_EXCEPTION',
                            params: [err.message]
                        })
                    })
                }
            });
        }
    };

    app.post('/api/query', midQuery(function (sql) {
        sql = sql.trim();
        if (sql[sql.length - 1] == ';') {
            sql = sql.substring(0, sql.length - 1);
        }
        console.log(sql);
        return sql;
    }));
};
exports.init_module = init_module;